from array import array
from random import random

# # 'd' means 'double', create 10^7 nums(double)
# random_nums = array('d', (random() for i in range(10 ** 7)))
# print(random_nums[-1])
# # save the array into a binary file
# fp = open('random_nums.bin', 'wb')
# # tofile() --> Save items as packed machine values to binary file f
# random_nums.tofile(fp)
# fp.close()
# # create a new empty array
# random_nums_copy = array('d')
# # fromfile() --> Append n items from binary file f interpreted as packed machine values
# fp = open('random_nums.bin', 'rb')
# random_nums_copy.fromfile(fp, 10 ** 7)
# fp.close()
# print(random_nums_copy[-1])
# # check the contents of two arrays
# if random_nums_copy == random_nums:
#     print('this two array have same content')

a = array('f', (random() for k in range(10)))
print("a.typecode --> ", a.typecode)
print("a --> ", a)
# .sort() don not support array, use follow instructions instead
sorted_a = array(a.typecode, sorted(a))
print("sorted_a -->", sorted_a)
# fromlist() --> list2array
lst = [1, 2, 3, 4]
print("lst --> ", lst)
# this step can not be omitted
b = array('i')
b.fromlist(lst)
print("fromlist(lst) --> ", b)
# insert(p, e) --> insert a element e in position p
b.insert(0, 0)
print("insert(0, 0) --> ", b)
# remove(e) --> remove element e from array by value
b.remove(0)
print("remove(0) --> ", b)
# pop([p]) --> remove and return the item in position p(default last)
res = b.pop()
print("pop() --> ", b, res)
# index(e) --> find the position of element e
idx = b.index(3)
print("b.index(3) --> ", idx)
# reverse()
b.reverse()
print("b.reverse() --> ", b)
# tolist() --> array2list
array2list = b.tolist()
print("b.tolist() --> ", array2list)
# list.__reversed__() --> for iterator
reversed_iter = [i for i in range(10)].__reversed__()
print(list(reversed_iter))